package com.wthink.hzgj.business.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wthink.hzgj.BusApplication
import com.wthink.hzgj.business.data.Business
import com.wthink.hzgj.data.Result
import com.wthink.hzgj.service.DevService
import com.wthink.hzgj.service.jt808.JT_0B09
import com.wthink.hzgj.station.data.Station
import com.wthink.hzgj.util.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class BusinessViewModel : ViewModel() {

    var busLineNo = -1

    var business = -1

    val businessList = MutableLiveData(emptyList<Business>())

    fun updateBusiness(businessType: String) {
        queryBusStateUntilSuccess()
        when (businessType) {
            "排班" -> {
                business = 1
            }
            "交班" -> {
                business = 2
            }
            "加油" -> {
                business = 3
            }
            "加气" -> {
                business = 4
            }
            "充电" -> {
                business = 5
            }
            "维修" -> {
                business = 6
            }
            "包车" -> {
                business = 7
            }
            "终止任务" -> {
                business = 8
            }
        }

        viewModelScope.launch(Dispatchers.IO) {
            val ret = DevService.send808(JT_0B09(busLineNo, "12345", business))
            withContext(Dispatchers.Main) {
                if (ret.success) {
                    toast(BusApplication.busContext, "上报成功")
                } else {
                    toast(BusApplication.busContext, ret.err.toString())
                }
            }
        }
    }

    fun start() {
        var array: Array<String> = arrayOf(
            "排班", "交班", "加油", "加气", "充电", "维修", "包车", "终止任务"
        )
        val arrayList = ArrayList<Business>()
        for (item in array) {
            arrayList.add(Business(item))
        }
       // businessList.postValue(arrayList)
    }

    fun queryBusStateUntilSuccess(delay: Long = 5000) {
        viewModelScope.launch(Dispatchers.IO) {
            while (isActive) {
                val ret = DevService.queryBusState()
                if (ret is Result.Success) {
                    busLineNo = ret.data.lineId.toInt()
                    break
                }
                kotlinx.coroutines.delay(delay)
            }
        }
    }
}